package com.demo.service;

import com.demo.MqConstants;
import com.demo.listener.EmailMessage;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Service
public class MqSendServiceImpl implements MqSendService {
    private static final Logger log = LoggerFactory.getLogger(MqSendServiceImpl.class);
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void send(EmailMessage message) {
        String msgId = message.getMsgId();
        // 发送消息
        Message<EmailMessage> messageFinal = MessageBuilder.withPayload(message).setHeader("KEYS", msgId).build();
        String destination = MqConstants.EMAIL_TOPIC;
        // log.info("成功发送消息,消息内容为:{},返回值为:{}", message, result);
        SendResult sendResult = rocketMQTemplate.syncSend(destination, messageFinal);
        if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
            log.error("send fail, message: {}", message);
        }
    }

    @Override
    public void sendWithTag(EmailMessage message) {
        String msgId = message.getMsgId();
        // 发送消息
        Message<EmailMessage> messageFinal = MessageBuilder.withPayload(message).setHeader("KEYS", msgId).build();
        String destination = MqConstants.EMAIL_TOPIC  + ":" + MqConstants.EMAIL_TAG;
//        destination = MqConstants.EMAIL_TOPIC  + ":" + MqConstants.DEMO_TAG;
        // log.info("成功发送消息,消息内容为:{},返回值为:{}", message, result);
        SendResult sendResult = rocketMQTemplate.syncSend(destination, messageFinal);
        if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
            log.error("send fail, message: {}", message);
        }
    }
}
